<#
	#   It is recommended to test the script on a local machine for its purpose and effects. 
	#   ManageEngine Endpoint Central will not be responsible for any 
	#   damage/loss to the data/setup based on the behavior of the script.
	#   Description: Script to automatically disable the local user accounts that have not logged in for 90 days.
	#   Parameters: ExcludeUsersList
    #   Ex : "Administrator,Sysadmin"
	#   Remarks:	The script has to be deployed as Computer Configuration
	#   Configuration Type - Computer
	
#>
 # Capture the exclusion list and construct the regex pattern (if provided)
if ($args.Count -gt 0 -and $args[0] -ne "") {
    $excludeUsers = $args[0] -split ','
    $ExcludeUsersPattern = "^((" + ($excludeUsers -join '|') + "))$"
} else {
    $ExcludeUsersPattern = $null
}

$currentDate = Get-Date 

$users = Get-LocalUser | Where-Object { 
   $_.Enabled -eq $true -and 
    ($ExcludeUsersPattern -eq $null -or $_.Name -notmatch $ExcludeUsersPattern) -and
    ($_.SID.Value -notlike '*-500')
}

foreach ($user in $users) {
    $name = $user.Name
    $lastLogon = $user.LastLogon
    
    if ($lastLogon) {
        $daysSinceLastLogon = ($currentDate - $lastLogon).Days
        if ($daysSinceLastLogon -gt 90) {
            Disable-LocalUser -Name $name
            Write-Output "User '$name' has been disabled. Last login was $daysSinceLastLogon days ago."
        }
    }
}